package com.fastjrun.util.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.fastjrun.util.AbstractIpUtil;
import com.fastjrun.util.IpUtil;

/**
 * @author Stan
 */
public class IpUtilWithIp138 extends AbstractIpUtil implements IpUtil {

    public String locateWanIp() {
        InputStream ins = null;
        try {
            URL url = new URL("https://ip.tool.lu");
            URLConnection con = url.openConnection();
            ins = con.getInputStream();
            InputStreamReader isReader = new InputStreamReader(ins);
            BufferedReader bReader = new BufferedReader(isReader);
            StringBuilder webContent = new StringBuilder();
            String str = null;
            while ((str = bReader.readLine()) != null) {
                webContent.append(str);
            }
            //IP请求结果
            String testResult = webContent.toString();
            String replaced = testResult.replace("当前IP: ", "");
            int indexOf = replaced.indexOf("归属地:");
            return indexOf != -1 ? replaced.substring(0, indexOf) : "";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
